/**
 * @file dataChannel.js
 * @Date 2023-10-29, 周日, 16:19
 * @description 文件说明
 *我的空间数据通道部分js文件
 */
$(function () {
    /******************************************初始化******************************************/
    const table=layui.table;
    // 选中的数据通道的id数组
    let channelIdList=[]
    // 数据通道查询参数
    let databaseParams={
        ownUserId:sessionStorage.getItem('UserId'),
        currPage:0,
        pageSize:10
    }
    // 数据通道表格实例
    const databaseTable= table.render({
        id:'dataSourceBaseTable',
        elem: '#dataSourceBaseTable'
        ,height: '.layui-tab-item'
        ,data:[]
        // ,page: true //开启分页
        ,cols: [[ //表头
            {type:'checkbox', width:60},
            {type:'numbers', title: '序号',}
            ,{field: 'resourceName', title: '名称'}
            ,{field: 'unit', title: '所属单位'}
            ,{field: 'depart', title: '所属部门'}
            ,{field: 'brief', title: '简介'}
            // ,{field: 'sourceNumber', title: '来源数量'}
            // ,{field: 'databaseType', title: '来源类型'}
            ,{field: 'status', title: '当前状态',templet:
                    function (d){
                        const status=d.status;
                        switch (status) {
                            case -2:
                                return `<span>审核失败</span>`
                            case -1:
                                return `<span>保存</span>`
                            case 0:
                                return `<span>正常</span>`
                            case 1:
                                return `<span>故障</span>`
                            case 2:
                                return `<span>未审核</span>`
                            case 3:
                                return `<span>未测试</span>`
                        }
                    }
            }
            // ,{field: 'remark', title: '备注'}
            ,{  title: '操作', width: 180, templet:function (d){
                    switch (d.status){
                        case -2:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
                        case -1:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						<a class="layui-btn layui-btn-warning layui-btn-xs text-white" lay-event="test">测试</a>
						`
                        case 0:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						<a class="layui-btn layui-btn-warning layui-btn-xs text-white" lay-event="test">测试</a>
						`
                        case 1:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
                        case 2:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
                        case 3:
                            return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						<a class="layui-btn layui-btn-warning layui-btn-xs text-white" lay-event="test">测试</a>
						`
                    }
                }
            },

        ]]
    })
    /******************************************事件处理部分******************************************/
    // 数据通道注册
    $("#rootRegistrat").click(function(){
        window.location.href = "./popupPage/rootRegister.html";
    })
    // 数据通道批量选中复选框
    table.on('checkbox(dataSourceBaseTableFilter)', function(obj){
        if (obj.type==='all'&&obj.checked){
            channelIdList=table.cache['dataSourceBaseTable'].map(item=>item.id);
            console.log('channelIdList', channelIdList)
        }else if (obj.type==='one'&&obj.checked){//选中
            channelIdList.push(obj.data.id)
            console.log('sourceIdList', channelIdList)
        }else if (obj.type==='all'&&!obj.checked){//取消选中
            channelIdList=[]
        }else if (obj.type==='one'&&!obj.checked){//取消选中
            // 查找值的索引
            const index = channelIdList.indexOf(obj.data.id);
            if (index !== -1) {
                channelIdList.splice(index, 1);
            }
        }
    });
    // 批量提交审核数据通道按钮
    $("#submitDataChannelAll").on('click',function (){
        console.log('channelIdList', channelIdList)
        if(channelIdList.length>0){
            $.ajax({
       timeout:30000,
                url: window.Http + '/datasourceBase/commit/'+channelIdList.join(','),
                type:'PUT' ,
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('提交成功')
                        channelIdList=[]

                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        }else {
            layer.msg('当前未选中数据')
        }
    })
    // 批量删除数据通道按钮
    $('#deleteDataChannelAll').on('click',function (){
       if (channelIdList.length>0){
           $.ajax({
       timeout:30000,
               url: window.Http + '/datasourceBase/'+channelIdList.join(','),
               type:'DELETE' ,
               headers: {
                   'Authorization': "Bearer " + sessionStorage.getItem('Token')
               },
               success: function (res) {
                   if (res.code === 200) {
                       layer.msg('删除成功')
                       channelIdList=[]
                       databaseTableRender(databaseParams)
                   } else {
                       layer.msg(res.msg)
                   }
               }
           })
       }else {
           layer.msg('当前未选中数据')
       }
    })
    // 数据通道表格 修改 删除测试操作
    layui.table.on('tool(dataSourceBaseTableFilter)', function(obj){
        const data = obj.data;
        console.log('data', data)
        if(obj.event === 'edit') {
            window.location.href=`./popupPage/rootRegister.html?id=${data.id}`
        }else if (obj.event==='delete'){
            $.ajax({
       timeout:30000,
                url: window.Http + `/datasourceBase/${data.id}`,
                type: 'DELETE',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                success: function (res) {
                    if (res.code===200){
                        layer.msg('删除成功');
                        databaseTableRender(databaseParams)
                    }else {
                        layer.msg(res.msg)
                    }
                }
            })
        }else if (obj.event==='test'){
            $.ajax({
       timeout:30000,
                url: window.Http + "/datasourceBase/check",
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data: {
                    sourceId: data.id
                },
                success: function (res) {
                    if (res.code){
                        layer.msg('测试通过');
                    }else {
                        layer.msg(res.msg)
                    }
                }
            })
        }
    })
    /******************************************功能函数部分******************************************/
    // 请求数据通道列表
    function databaseListReq(params){
        return new Promise((function (resolve, reject) {
            $.ajax({
       timeout:30000,
                url: window.Http + "/datasourceBase/list",
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data:params,
                success: function (res) {
                    if (res.code===200){
                        resolve(res)
                    }else {
                        layer.msg(res.msg)
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                    }
                }
            })
        }))
    }
    // 数据通道表格和分页渲染
    function databaseTableRender(parame){
        databaseListReq(parame).then(res=>{
            databaseTable.reload({data:res.rows})
            layui.laypage.render({
                elem: 'dataSourceBaseTablePage', //注意，这里的 test1 是 ID，不用加 # 号
                count: res.total, //数据总数，从服务端得到
                limit: 10,
                groups: 5,
                jump: function (obj, first) {
                    if(!first){
                        console.log('obj.curr', obj.curr)
                        parame.currPage=obj.curr
                        databaseListReq(parame).then(res=>{
                            databaseTable.reload({data:res.rows})
                        });
                    }
                }
            });
        })
    }
    // 数据通道统计信息
    function requestStatistic(Type){
        $.ajax({
       timeout:30000,
            url: window.Http + "/count/personal/data/table",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: { type: Type,ownUserId:sessionStorage.getItem('UserId') },
            success: function (res) {
                if(res.code == 200){
                    if(Type === 4){
                        $('.datasourceTotal').html(res.data.total||0);
                        $('.datasourceStatus').html(res.data.normal||0);

                    }else{
                        $('.databaseTotal').html(res.data.total||0);
                        $('.databaseStatus').html(res.data.normal||0);
                    }
                }
            }
        })
    }
    requestStatistic(0);//数据通道
    // 初始化渲染表格和分页
    databaseTableRender(databaseParams)
})